import React from 'react';
import { Button, Form, Input, message, Upload } from 'antd';
import type { FormProps } from "antd";
import { httpPost } from '@utils/HttpUtil';
import { getUploadUrl, randomColor } from '@utils/WeStudyUtil';
import SelectKnowledgeTree from 'src/common/component/SelectKnowledgeTree';
import { UploadOutlined } from "@ant-design/icons";

type FieldType = {
  knowledge?: string;
  knowledgeImg?: any;
  explainImg?: any;
  pid?: any;
  color?: string;
};

const FunctionCreateKnowledge: React.FC = () => {

  const onFinish: FormProps<any>["onFinish"] = (values) => {
    if(!values.color){
      values.color = randomColor();
    }
    var resData = httpPost("/knowledge/submitKnowledge", values).data;
    if(resData.status){
      message.success("新增知识点成功");
    }else{
      message.error(resData.msg);
    }
  };

  const [form] = Form.useForm();

  const selectKnowledgeTree = (value: any) => {
    form.setFieldsValue({pid: value[0]});
  };

  const normFile = (e:any) =>{
    if(Array.isArray(e)){
        return e;
    }
    return e && e.fileList;
  }
  
  const uploadUrl = getUploadUrl();
  

  return (
    <>
      <Form
        name="basic"
        form={form}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 20 }}
        style={{ maxWidth: 1000, marginTop: 40 }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item<FieldType> label="上级知识点" name="pid">
          <SelectKnowledgeTree onChange={selectKnowledgeTree} />
        </Form.Item>

        <Form.Item<FieldType>
          label="知识点"
          name="knowledge"
          rules={[{ required: false, message: "请输入知识点!" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item<FieldType>
          label="知识点（图片）"
          name="knowledgeImg"
          // 下面两条必须存在
          valuePropName="fileList"
          getValueFromEvent={normFile}
        >
          <Upload
            action={uploadUrl}
            listType="picture"
            maxCount={1}
          >
            <Button type="primary" icon={<UploadOutlined />}>
              上传内容截图
            </Button>
          </Upload>
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type="primary" htmlType="submit">
            新增知识点
          </Button>
        </Form.Item>
      </Form>
    </>
  );
};

export default FunctionCreateKnowledge;